package com.example.androidproject;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.MenuItem;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import com.example.androidproject.chat.ChatFragment;
import com.example.androidproject.chat.pojo.ChatGroupInfo;
import com.example.androidproject.databinding.ActivityMainBinding;
import com.example.androidproject.databinding.DialogChatInviteBinding;
import com.example.androidproject.file.FileFragment;
import com.example.androidproject.my.MyFragment;
import com.example.androidproject.online.OnlineFragment;
import com.example.androidproject.online.activity.OnlineChatActivity;
import com.example.androidproject.online.pojo.ChatInfo;
import com.example.androidproject.sqlite.GroupRepository;
import com.example.androidproject.sqlite.UserRepository;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.google.gson.Gson;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class MainActivity extends ImmerseActivity {
    private ActivityMainBinding binding;
    private FragmentManager manager;
    private ChatFragment chatFragment;
    private FileFragment fileFragment;
    private OnlineFragment onlineFragment;
    private MyFragment myFragment;
    private static final int BROADCAST_PORT = 9876;
    private AlertDialog dialog;
    private DialogChatInviteBinding dialogBinding;
    private String TAG = "MainActivity...";
    private String localIpAddress;
    private ExecutorService executorService = Executors.newCachedThreadPool();
    private ArrayList<ChatGroupInfo> chatGroupInfos;
    private UserRepository.User user;
    private String userJson;
    private GroupRepository groupRepository;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        //初始化
        chatGroupInfos = new ArrayList<>();
        manager = getSupportFragmentManager();
        chatFragment = new ChatFragment();
        fileFragment = new FileFragment();
        onlineFragment = new OnlineFragment();
        myFragment = new MyFragment();
        replaceFragment(chatFragment);
        groupRepository = new GroupRepository(this);

        localIpAddress = getLocalIpAddress(binding.getRoot().getContext());
        SharedPreferences sharedPreferences = getSharedPreferences("userinfo", Context.MODE_PRIVATE);
        String username = sharedPreferences.getString("username", null);
        user=new UserRepository.User();
        user.setUsername(username);
        user.setUserIp(localIpAddress);
        SharedPreferences.Editor edit = sharedPreferences.edit();
        Gson gson = new Gson();
        userJson = gson.toJson(user);
        edit.putString("user",userJson);
        edit.apply();

        initAlertDialog();
        executorService.submit(this::receiveBroadcast);

        binding.bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                switch (item.getItemId()) {
                    case R.id.b1:
                        replaceFragment(chatFragment);
                        binding.topView.setText("消息");
                        // Handle home action
                        return true;
                    case R.id.b2:
                        replaceFragment(fileFragment);
                        binding.topView.setText("文件");
                        // Handle dashboard action
                        return true;
                    case R.id.b3:
                        replaceFragment(onlineFragment);
                        binding.topView.setText("在线");
                        // Handle notifications action
                        return true;
                    case R.id.b4:
                        replaceFragment(myFragment);
                        binding.topView.setText("我的");
                        return true;
                }
                return false;
            }
        });

    }

    private void replaceFragment(Fragment fragment) {
        Log.e(TAG, "list: " + chatGroupInfos.toString());
        FragmentTransaction transaction = manager.beginTransaction();
        transaction.replace(R.id.framalayout, fragment);
        transaction.commit();
    }

    private void receiveBroadcast() {
        DatagramSocket socket = null;
        try {
            socket = new DatagramSocket(BROADCAST_PORT);
            byte[] buffer = new byte[1024];

            while (!Thread.currentThread().isInterrupted()) {
                DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
                socket.receive(packet);
                String message = new String(packet.getData(), 0, packet.getLength());
                InetAddress clientAddress = packet.getAddress();
                Log.e(TAG, "Received packet from: " + clientAddress.getHostAddress());
                Log.e(TAG, "Message: " + message);


                if ("FOUND".equals(message)) {
                    DatagramPacket responsePacket = new DatagramPacket(
                            userJson.getBytes(),
                            userJson.length(),
                            clientAddress,
                            packet.getPort()
                    );
                    socket.send(responsePacket);
                } else {
                    Gson gson = new Gson();
                    UserRepository.User userClass = gson.fromJson(message, UserRepository.User.class);
                    if(userClass.getUserIp().equals(localIpAddress)){
                        new Handler(Looper.getMainLooper()).post(() -> {
                            dialogBinding.accept.setOnClickListener(v -> {
                                handleButtonClick("YES", clientAddress, packet.getPort());
                                dialog.dismiss();
                                Intent intent = new Intent(binding.getRoot().getContext(), OnlineChatActivity.class);
                                intent.putExtra("identity", "client");
                                intent.putExtra("serverAddress", clientAddress.getHostAddress());
                                startActivity(intent);

                                String tableName = "t"+clientAddress.getHostAddress().replace(".", "");
                                groupRepository.insertGroup(tableName,user.getUsername(),user.getUserIp());
                            });
                            dialogBinding.deny.setOnClickListener(v -> {
                                handleButtonClick("NO", clientAddress, packet.getPort());
                                dialog.dismiss();
                            });
                            dialog.show();
                        });
                    }
                }
            }
        } catch (IOException e) {
            Log.e(TAG, "Error in receiveBroadcast", e);
        } finally {
            if (socket != null && !socket.isClosed()) {
                socket.close();
            }
        }
    }

    private void handleButtonClick(String response, InetAddress inetAddress, int port) {
        executorService.submit(() -> {
            try {
                DatagramSocket socket = new DatagramSocket();
                DatagramPacket responsePacket = new DatagramPacket(
                        response.getBytes(),
                        response.length(),
                        inetAddress,
                        port
                );
                socket.send(responsePacket);
                socket.close();
            } catch (IOException e) {
                Log.e(TAG, "Error in handleButtonClick", e);
            }
        });
    }

    private void initAlertDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(binding.getRoot().getContext());
        dialogBinding = DialogChatInviteBinding.inflate(getLayoutInflater());
        builder.setView(dialogBinding.getRoot());
        dialog = builder.create();
    }

    public static String getLocalIpAddress(Context context) {
        try {
            WifiManager wifiManager = (WifiManager) context.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
            WifiInfo wifiInfo = wifiManager.getConnectionInfo();
            int ipAddress = wifiInfo.getIpAddress();

            if (ipAddress != 0) {
                return String.format("%d.%d.%d.%d",
                        (ipAddress & 0xff),
                        (ipAddress >> 8 & 0xff),
                        (ipAddress >> 16 & 0xff),
                        (ipAddress >> 24 & 0xff));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        executorService.shutdownNow(); // 关闭 ExecutorService 并中断所有任务
    }

//    public void setDataToChatFragment(ChatGroupInfo chatGroupInfo) {
//        boolean isContain = false;
//        for (ChatGroupInfo groupInfo : chatGroupInfos) {
//            if (groupInfo.getGroupName().equals(chatGroupInfo.getGroupName())) {
//                isContain = true;
//                break;
//            }
//        }
//        if (!isContain) {
//            chatGroupInfos.add(chatGroupInfo);
//        }
//    }
}